<?php
namespace app\common\loglic;

use app\common\loglic\Model;

class Type extends Model
{
    //自增更新
    public function incUpdate($pkId=0, $field='detail_view', $num=1, $time=0)
    {
        if(!$pkId){
            return 0;
        }
        return db('type')->where('type_id',$pkId)->setInc($field, abs($num), $time);
    }

    //自减
    public function decUpdate($pkId=0, $field='detail_view', $num=1, $time=0)
    {
        if(!$pkId){
            return 0;
        }
        return db('type')->where('type_id',$pkId)->setDec($field, abs($num), $time);
    }

    //更新字段值
    public function fieldUpdate($ids=[], $field='type_status', $value='normal')
    {
        if(!$ids || !$value){
            return false;
        }
        return db('type')->where('type_id','in',$ids)->setField($field, $value);
    }

    //按主键ID删除
    public function deleteId($typeId=0)
    {
        if(!$typeId){
            return 0;
        }
        if($this->getChildren($typeId)){
            $this->error = '请先删除子类';
            return 0;
        }
        return $this->modelDelete('common/Type', ['type_id'=>$typeId], 'typeMap');
    }

    //更新统计
    public function updateCount()
    {
        $this->dbUpdate('type',[['type_id','gt',0]],['type_count'=>0]);
        //分组查询统计
        $item = db('type_map')
        ->field('type_mp_tid as type_id,count(type_mp_tid) as type_count')
        ->where('type_mp_tid > 0')
        ->group('type_mp_tid')
        ->order('type_count desc')
        ->select();
        //批量更新
        if($item){
            return model('common/Type')->allowField(true)->isUpdate(true)->saveAll($item);
        }
        return 0;
    }

    //获取该分类的子集列
    public function getChildren($typeId=0)
    {
        return db('type')->limit(0)->where([
            ['type_parent','eq',$typeId],
        ])->order([
            'type_id' => 'desc',
        ])->column('type_name','type_id');
    }

    //获取该分类的所有子集
    public function getChildrens($typeId=0)
    {
        return xfChildrens($this->listAll('type_id,type_name,type_parent'),$typeId,1,'type_id','type_parent');
    }

    //获取该分类的所有父集
    public function getParents($typeId=0)
    {
        $typeParent = $this->dbValue('type',['type_id'=>$typeId],'type_parent');
        if($typeParent){
            return xfParents($this->listAll('type_id,type_name,type_parent'),$typeParent,'type_id','type_parent');
        }
        return [];
    }

    //获取所有分类
    public function listAll($field='type_id,type_name,type_parent')
    {
        return db('type')->field($field)->limit(0)->order([
            'type_id' => 'desc',
        ])->select();
    }
}